package net.huashitong.node.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.entity.ProIndustryType;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.filter.ProjectFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.service.ProIndustryTypeService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.node.utile.NodeNewschedulesUtil;
import net.huashitong.user.entity.Collection;
import net.huashitong.user.filter.CollectionFilter;
import net.huashitong.user.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/app/nodesApp")
public class NodesAppController extends JsonBaseController {

    public static final String EARLY = "2";     //超前
    public static final String DELAY = "1";     //逾期
    public static final String NORMAL = "0";    //正常
    public static final String NOFINISH = "-1";  //未开始
    public static final String UNDERWAY="3";     //进行中

    @Autowired
    private NewProjectsService newProjectsService;

    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;

    @Autowired
    private ProIndustryTypeService proIndustryTypeService;

    @Autowired
    private CollectionService collectionService;

    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 获取节点信息列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryNodesListByProjectId")
    public Message queryNodesListByProjectId(@RequestBody ProjectFilter filter) {
        String userId = filter.getUserId();
        String projectId = filter.getProjectId();
        CollectionFilter cFilter = new CollectionFilter();
        cFilter.setUserId(userId);
        cFilter.setProjectId(projectId);
        //判断项目是否收藏
        Collection collection = collectionService.getByUserIdAndSome(cFilter);
        Map<String, Object> map = new HashMap<>();
        if(ObjectUtils.isNotBlank(collection)){
            map.put("isCollect","1");
        }else{
            map.put("isCollect","0");
        }
        NewProjects np = newProjectsService.getById(filter.getProjectId());
        map.put("sysId", np.getSysId());
        map.put("name", np.getName());
        map.put("resDept", np.getResDept());
        map.put("resUser", np.getResUser());
        map.put("natureType", np.getNatureType());
        map.put("money", np.getMoney());
        map.put("status", np.getStatus());
        map.put("address", np.getAddress());
        map.put("describes", np.getDescribes());
        map.put("planBeginDate", np.getPlanBeginDate());//开始时间
        map.put("contactName", np.getContactName());
        map.put("contactPhone", np.getContactPhone());
        ProIndustryType t1 = proIndustryTypeService.queryByTypeCode(np.getIndustryType());
        map.put("industryType", t1.getTypeName());
        ProIndustryType t2 = proIndustryTypeService.queryByTypeCode(np.getProjectType());
        map.put("projectType", t2.getTypeName());
        ProIndustryType t3 = proIndustryTypeService.queryByTypeCode(np.getSchedCode());
        map.put("schedCode", t3.getTypeName());
        //小节点总是
        int smallTotal = 0;
        int smallFinishTotal = 0;
        int advanceTotal = 0;
        int normalTotal = 0;
        int delayTotal = 0;
        int underwayTotal=0;
        int notBeginList=0;
        List<Map<String, Object>> List1 = new ArrayList<Map<String, Object>>();
        List<NodeNewschedules> list1 = nodeNewschedulesService.getNodeInfo(filter.getProjectId(), "1", "", "1");
        List<NodeNewschedules> list2 = nodeNewschedulesService.getNodeInfo(filter.getProjectId(), "2", "", "1");

        //节点时间状态更新

        new NodeNewschedulesUtil().updateNodesTimeState(list2, np);
        //小节点
//        updateNodesTimeState(list2,np);

        //大节点
        for (NodeNewschedules n1 : list1) {
            String flag = "0";
            int totalFactTime = 0;  //总的实际时间
            int totalPlanTime = 0;  //总的计划时间
            boolean isStart = false;//节点是否开始，默认未开始
            for (NodeNewschedules smallNode : list2) {

                if (n1.getNodeId().equals(smallNode.getNodeIds())) {
                    if (!isStart && !"-1".equals(smallNode.getIsDelay())) {
                        isStart = true;
                    }

                    if ("2".equals(smallNode.getStatus()) && StringUtils.isNotBlank(smallNode.getFactTime()) && StringUtils.isNotBlank(smallNode.getPlanTime())) {
                        totalFactTime += Integer.parseInt(smallNode.getFactTime());
                        totalPlanTime += Integer.parseInt(smallNode.getPlanTime());
                    }
                }
            }
            if (!isStart) {
                n1.setIsDelay(NOFINISH);
                continue;
            }
            if (totalFactTime > totalPlanTime) {        //实际时间大于计划时间----逾期
                n1.setIsDelay(DELAY);
            } else if (totalFactTime < totalPlanTime) {  //实际时间小于计划时间----超前
                n1.setIsDelay(EARLY);
            } else if (totalFactTime == totalPlanTime) { //实际时间等于计划时间----正常
                n1.setIsDelay(NORMAL);
            }
            n1.setCreateDate(np.getCreateDate());
        }
        //批量更新时间状态
//        nodeNewschedulesService.batchUpdateObject(list1);

        smallTotal = list2.size();
        for (NodeNewschedules nns : list1) {
            List<NodeNewschedules> List2 = new ArrayList<NodeNewschedules>();
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("sysId", nns.getSysId());
            map1.put("nodeId", nns.getNodeId());
            map1.put("preNodeId", nns.getPreNodeId());
            map1.put("nodeName", nns.getNodeName());
            map1.put("resDept", nns.getResDept());
            map1.put("resUser", nns.getResUser());
            map1.put("planBeginDate", nns.getPlanBeginDate());
            map.put("factFinishDate", nns.getFactFinishDate());
            map1.put("nodeType", nns.getNodeType());
            map1.put("status", nns.getStatus());
            map1.put("state", nns.getState());
            map1.put("isDelay", nns.getIsDelay());
            for (NodeNewschedules nns2 : list2) {
                if (nns.getNodeId().equals(nns2.getNodeIds())) {
                    if ("2".equals(nns2.getStatus())) {
                        smallFinishTotal++;
                        if (ObjectUtils.isNotBlank(nns2.getPlanBeginDate()) && ObjectUtils.isNotBlank(nns2.getPlanTime()) && ObjectUtils.isNotBlank(nns2.getFactFinishDate())) {
                            int zxz = nns2.getFactFinishDate().compareTo(DateUtil.addDays(nns2.getPlanBeginDate(), Integer.parseInt(nns2.getPlanTime()) - 1));
                            if (zxz > 0) {
                                delayTotal++;
//                                continue;
                            } else if (zxz == 0) {
                                normalTotal++;
//                                continue;
                            } else if (zxz < 0) {
                                if (Integer.parseInt(nns2.getFactTime()) == Integer.parseInt(nns2.getPlanTime())) {
                                    normalTotal++;
//                                    continue;
                                } else if (Integer.parseInt(nns2.getFactTime()) > Integer.parseInt(nns2.getPlanTime())) {
                                    delayTotal++;
//                                    continue;
                                } else if (Integer.parseInt(nns2.getFactTime()) < Integer.parseInt(nns2.getPlanTime())) {
                                    advanceTotal++;
//                                    continue;
                                }
                            }
                        } else {
                            normalTotal++;
                        }
                    }
                    if ("1".equals(nns2.getStatus())) {
                        if (ObjectUtils.isNotBlank(nns2.getPlanBeginDate()) && ObjectUtils.isNotBlank(nns2.getPlanTime())) {
                            int zxz = DateUtil.getDate().compareTo(DateUtil.addDays(nns2.getPlanBeginDate(), Integer.parseInt(nns2.getPlanTime()) - 1));
                            if (zxz > 0) {
                                delayTotal++;
//                                continue;
                            } else if (zxz == 0) {
                               // normalTotal++;
                                underwayTotal++;
//                                continue;
                            }
                        }
                    }
                    if("0".equals(nns2.getStatus())){
                        notBeginList++;
                    }
                    List2.add(nns2);
                }

            }

            map1.put("childNodesList", List2);
            List1.add(map1);
        }
        map.put("lists", List1);
        map.put("smallTotal", smallTotal);//节点总数
        map.put("smallFinishTotal", smallFinishTotal);//已完成总数
        map.put("advanceTotal", advanceTotal);//超前总数
        map.put("normalTotal", normalTotal);//正常总数
        map.put("delayTotal", delayTotal);//延期总数
        map.put("notBeginList",notBeginList);//未开始总数
        map.put("underwayTotal",underwayTotal);//进行中总数
        return coverMessage("200", "成功", map);
    }

    @ResponseBody
    @RequestMapping(value = "/fileterNode", method = RequestMethod.POST)
    public Message getNodesTimeDetail(@RequestBody NewProjectsFilter filter) {
        //-1:超前  0:正常   1:逾期  2:未开始  3:进行中
        String projectId = filter.getProjectId();
        String type = filter.getType();
        List<Map<String, Object>> leadNodes = new ArrayList<Map<String, Object>>(); //超前
        List<Map<String, Object>> normalNodes = new ArrayList<Map<String, Object>>();                 //正常
        List<Map<String, Object>> delayNodes = new ArrayList<Map<String, Object>>();//逾期
        List<Map<String, Object>> notBeginNodes = new ArrayList<Map<String, Object>>();//未开始
        List<Map<String, Object>> underwayNodes = new ArrayList<Map<String, Object>>();//进行中
        //需要的所有小节点
        List<NodeNewschedules> allNode = nodeNewschedulesService.queryListByProjectId(projectId, "2", null, "1", null);

        //所有完成的小节点
        List<NodeNewschedules> nodeList = new ArrayList<NodeNewschedules>();
        //所有未完成（已开始、未开始）的小节点
        List<NodeNewschedules> nodeList0 = new ArrayList<NodeNewschedules>();

        for (NodeNewschedules node : allNode) {
            if (!nodeList.contains(node.getNodeIds()) && !"0".equals(node.getNodeIds()) && "2".equals(node.getStatus())) {
                nodeList.add(node);
            }
            if (!nodeList0.contains(node.getNodeIds()) && !"0".equals(node.getNodeIds()) && !"2".equals(node.getStatus())) {
                nodeList0.add(node);
            }
        }
        //所有未完成（已开始、未开始）的小节点
        for (NodeNewschedules n0 : nodeList0) {
            Map<String, Object> time0Map = new HashMap<String, Object>();
            if (ObjectUtils.isNotBlank(n0.getPlanBeginDate()) && ObjectUtils.isNotBlank(n0.getPlanTime())) {
                int zxz = DateUtil.getDate().compareTo(DateUtil.addDays(n0.getPlanBeginDate(), Integer.parseInt(n0.getPlanTime()) - 1));
                if (zxz > 0) {
                    time0Map.put("NodeId", n0.getNodeId());
                    time0Map.put("NodeName", n0.getNodeName());
                    time0Map.put("ResUser", n0.getResUser());
                    delayNodes.add(time0Map);
                } else if (zxz == 0) {
                    if("1".equals(n0.getStatus())){
                        time0Map.put("NodeId", n0.getNodeId());
                        time0Map.put("NodeName", n0.getNodeName());
                        time0Map.put("ResUser", n0.getResUser());
                        underwayNodes.add(time0Map);
                    }else{
                        time0Map.put("NodeId", n0.getNodeId());
                        time0Map.put("NodeName", n0.getNodeName());
                        time0Map.put("ResUser", n0.getResUser());
                        normalNodes.add(time0Map);
                    }

                }else{
                    time0Map.put("NodeId", n0.getNodeId());
                    time0Map.put("NodeName", n0.getNodeName());
                    time0Map.put("ResUser", n0.getResUser());
                    notBeginNodes.add(time0Map);
                }
            }else{
                time0Map.put("NodeId", n0.getNodeId());
                time0Map.put("NodeName", n0.getNodeName());
                time0Map.put("ResUser", n0.getResUser());
                notBeginNodes.add(time0Map);
            }
        }
        //所有已完成的小节点
        for (NodeNewschedules n : nodeList) {
            Map<String, Object> timeMap = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(n.getFactTime()) && StringUtils.isNotBlank(n.getPlanTime())) {
                int factTime = Integer.parseInt(n.getFactTime());
                int planTime = Integer.parseInt(n.getPlanTime());
                if (factTime > planTime) {        //实际时间大于计划时间----逾期
                    timeMap.put("NodeId", n.getNodeId());
                    timeMap.put("NodeName", n.getNodeName());
                    timeMap.put("ResUser", n.getResUser());
                    delayNodes.add(timeMap);
                } else if (factTime < planTime) {  //实际时间大于计划时间----超前
                    timeMap.put("NodeId", n.getNodeId());
                    timeMap.put("NodeName", n.getNodeName());
                    timeMap.put("ResUser", n.getResUser());
                    leadNodes.add(timeMap);
                } else if (factTime == planTime) { //实际时间大于计划时间----正常
                    timeMap.put("NodeId", n.getNodeId());
                    timeMap.put("NodeName", n.getNodeName());
                    timeMap.put("ResUser", n.getResUser());
                    normalNodes.add(timeMap);
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if ("-1".equals(type)) {
            map.put("nodeList", leadNodes);
        } else if ("0".equals(type)) {
            map.put("nodeList", normalNodes);
        } else if ("1".equals(type)) {
            map.put("nodeList", delayNodes);
        } else if("2".equals(type)){
            map.put("nodeList", notBeginNodes);
        }else if("3".equals(type)){
            map.put("nodeList", underwayNodes);
        }else{
            map.put("nodeList", null);
        }

        return coverMessage("200", "获取成功", map);
    }

    //节点时间状态更新(限小节点)

}
